package co.fitstart.weapp.api.web.controller.order;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.coupon.Coupon;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.order.Order;
import co.fitstart.entity.order.PaymentStatus;
import co.fitstart.entity.user.User;
import co.fitstart.weapp.api.service.CouponService;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.OrderService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author dan
 *
 */
@RestController
@RequestMapping("/orders")
public class OrderController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private CouponService couponService;
    
    @Autowired
    private CourseRoundService courseRoundService;
    
    /**
     * 
     * @param unionid
     * @param status
     * @return
     */
    @RequestMapping(path = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult list(@RequestParam("unionid") String unionid,
                             @RequestParam(value = "paymentStatus", required = false, defaultValue = "unpaid") String status) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            
            PaymentStatus paymentStatus = PaymentStatus.aliasOf(status);
            List<Order> orders = orderService.list(user, paymentStatus);
            
            httpResult.success().message("获取数据成功")
                                .data("user", user)
                                .data("orders", orders)
                                .data("paymentStatus", paymentStatus.isUnpaid() ? 0 : 1);
            
        } catch (Exception e) {
            
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;

    }
    
    /**
     * 
     * @param unionid
     * @param orderId
     * @return
     */
    @RequestMapping(path = "/{orderId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult view(@RequestParam("unionid") String unionid,
                           @PathVariable("orderId") Long orderId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            Order order = orderService.load(orderId);
            Long userId = user.getId();
            
            // goes to error page when not match
            if(!order.matches(userId)) {
                httpResult.fail("500").message("用户信息与订单信息不匹配");
            } else {
                
                if(order.getOrderType().isOnline() && order.getPaymentStatus().isPaid() && order.isOnlineYear()) {
                    List<Coupon> unused = new ArrayList<>();
                    List<String> usedCouponIds = new ArrayList<>();
                    int giveAmount = 0;
                    Long doneeId = null;
                    
                    List<Coupon> coupons = couponService.listCoupon(order);
                    for(Coupon coupon : coupons) {
                        if(userId.equals(coupon.getUserId())) {
                            if(coupon.getStatus().isUsed()) {
                                usedCouponIds.add(coupon.getId() + "");
                            } else {
                                unused.add(coupon);
                            }
                        } else {
                            giveAmount++;
                            doneeId = coupon.getUserId();
                        }
                    }
                    
                    //未使用优惠券
                    httpResult.data("unused", unused);
                    
                    //已购买课程
                    if(usedCouponIds.size() > 0) {
                        List<CourseRound> finishedCourseRounds = courseRoundService.list(usedCouponIds, true);
                        List<CourseRound> onGoingCourseRounds = courseRoundService.list(usedCouponIds, false);
                        
                        httpResult.data("finishedCourseRounds", finishedCourseRounds)
                                  .data("onGoingCourseRounds", onGoingCourseRounds);
                    }
                    
                    //转赠优惠券数量
                    httpResult.data("give", giveAmount);
                    
                    ////受赠人姓名
                    if(doneeId != null) {
                        User donee = userService.load(doneeId);
                        
                        if(donee != null) {
                            httpResult.data("donee", donee.getName() == null ? donee.getMobile() : donee.getName());
                        }
                    }
                }
                
                httpResult.success().message("获取数据成功").data("order", order.orderDetailDescribe());
                
            }
            
        } catch (Exception e) {
            
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
    
}
